export default {
    ws: {},
    setWs: function(newWs) {
        this.ws = newWs
    },
    start(){// 发送心跳
        clearInterval(this.timeoutObj)
        this.timeoutObj = setInterval(() => {
            if (this.ws && this.ws.readyState == 1) {
                console.log('发送心跳')
                this.ws.send(JSON.stringify({
                    "linkId": "",
                    "fromUser": 0,
                    "toUser": 0,
                    "content": "",
                    "type": 0,
                    "nickname": "",
                    "avatar": ""
                }));
            }
        }, 10 *1000)//十秒发一次
    },
    localSocket(userId) {//连接ws
        if ("WebSocket" in window) {
            // console.log("您的浏览器支持 WebSocket!");
            // location.host
            this.ws = new WebSocket(`ws://123.57.251.41:8080/websocket/${userId}`);
            // this.ws = new WebSocket(`ws://localhost:3000`);
            this.setWs(this.ws);
            this.ws.onopen = ()=>{
                console.log('websocket连接成功');

                //连接上之后要发心跳包
                this.start()
            };

            this.ws.onclose = function () {
                // 关闭 websocket
                console.log("连接已关闭...");
                //断线重新连接
                setTimeout(() => {
                    this.localSocket(userId);
                }, 2000);
            };
        } else {
            // 浏览器不支持 WebSocket
            console.log("您的浏览器不支持 WebSocket!");
            this.openNotificationWithIcon('error', '浏览器', '您的浏览器不支持显示消息请更换', 1,1)
        }
    },
} 